package com.zero2oneit.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zero2oneit.mall.common.bean.member.MemberSign;
import com.zero2oneit.mall.common.bean.member.MemberSignRecord;
import com.zero2oneit.mall.common.bean.member.MemberSignRule;
import com.zero2oneit.mall.common.query.member.MemberSignQueryObject;
import com.zero2oneit.mall.common.utils.R;
import com.zero2oneit.mall.common.utils.bootstrap.BoostrapDataGrid;
import com.zero2oneit.mall.member.service.MemberSignRecordService;
import com.zero2oneit.mall.member.service.MemberSignRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zero2oneit.mall.member.mapper.MemberSignMapper;
import com.zero2oneit.mall.member.service.MemberSignService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 *
 * @author Tg
 * @email zero2oneit@163.com
 * @date 2021-05-13
 */
@Service
public class MemberSignServiceImpl extends ServiceImpl<MemberSignMapper, MemberSign> implements MemberSignService {

    @Autowired
    private MemberSignMapper memberSignMapper;

    @Autowired
    private MemberSignRecordService signRecordService;

    @Autowired
    private MemberSignService memberSignService;

    @Autowired
    private MemberSignRuleService signRuleService;

    @Override
    public BoostrapDataGrid signList(MemberSignQueryObject qo) {
        int total = memberSignMapper.selectTotal(qo);
        return new BoostrapDataGrid(total, total ==0 ? Collections.EMPTY_LIST : memberSignMapper.selectAll(qo));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R sign(MemberSign qo) {
        memberSignService.saveOrUpdate(qo);
        signRecordService.save(new MemberSignRecord(null, qo.getMemberId(), qo.getSignTime(), qo.getPoint()));
        return R.ok("签到成功");
    }

    @Override
    public R load(Long memberId) {
        QueryWrapper<MemberSignRule> wrapper = new QueryWrapper();
        MemberSignRule signRule = signRuleService.getOne(wrapper);
        QueryWrapper<MemberSign> wrappers = new QueryWrapper();
        wrappers.eq("member_id", memberId);
        MemberSign memberSign = memberSignService.getOne(wrappers);
        Map map = new HashMap();
        map.put("rule", signRule);
        map.put("sign", memberSign != null ? memberSign : JSON.parse("{\"id\":null,\"memberId\":\""+memberId+"\",\"signTime\":null,\"signCount\":0,\"signAmount\":0,\"signPoints\":0}"));
        return R.ok("加载成功", map);
    }

}